<template>
  <div class="purchase-smart-alerts" v-if="alerts.length > 0">
    <el-card class="alerts-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><Bell /></el-icon>
          <span>采购管理智能提醒</span>
        </div>
      </template>
      <div class="alerts-content">
        <div 
          v-for="alert in alerts" 
          :key="alert.id"
          class="alert-item"
          :class="`alert-${alert.type}`"
          @click="handleAlertClick(alert)"
        >
          <el-icon :size="16" :color="getAlertColor(alert.type)">
            <component :is="getAlertIcon(alert.type)" />
          </el-icon>
          <div class="alert-text">
            <div class="alert-title">{{ alert.title }}</div>
            <div class="alert-description">{{ alert.description }}</div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed } from '@vue/runtime-core'
import { Bell, Warning, DocumentDelete, TrendCharts, InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

interface Alert {
  id: string
  type: 'delayedDelivery' | 'largeAmount' | 'frequentSupplier' | 'qualityIssue'
  title: string
  description: string
  priority: 'high' | 'medium' | 'low'
  records?: any[]
}

interface Props {
  purchaseRecords: any[]
}

const props = defineProps<Props>()
const emit = defineEmits(['alert-click'])

// 计算智能提醒
const alerts = computed(() => {
  const alerts: Alert[] = []
  
  // 检查延期交货
  const delayedDeliveries = checkDelayedDeliveries(props.purchaseRecords)
  if (delayedDeliveries.length > 0) {
    alerts.push({
      id: 'delayed-deliveries',
      type: 'delayedDelivery',
      title: `发现${delayedDeliveries.length}笔延期交货`,
      description: '部分采购订单已超过预计交货时间，请及时跟进',
      priority: 'high',
      records: delayedDeliveries
    })
  }
  
  // 检查大额采购
  const largeAmountRecords = checkLargeAmountRecords(props.purchaseRecords)
  if (largeAmountRecords.length > 0) {
    alerts.push({
      id: 'large-amount-records',
      type: 'largeAmount',
      title: `发现${largeAmountRecords.length}笔大额采购`,
      description: '采购金额较大，请关注资金支付情况',
      priority: 'medium',
      records: largeAmountRecords
    })
  }
  
  // 检查频繁供应商
  const frequentSuppliers = checkFrequentSuppliers(props.purchaseRecords)
  if (frequentSuppliers.length > 0) {
    alerts.push({
      id: 'frequent-suppliers',
      type: 'frequentSupplier',
      title: `发现${frequentSuppliers.length}个频繁合作供应商`,
      description: '部分供应商采购频率较高，请关注合作关系',
      priority: 'medium',
      records: frequentSuppliers
    })
  }
  
  return alerts
})

// 检查延期交货（超过预计交货时间7天）
const checkDelayedDeliveries = (records: any[]) => {
  const delayedRecords: any[] = []
  const today = new Date()
  
  records.forEach(record => {
    // 假设有一个expectedDeliveryDate字段表示预计交货日期
    if (record.expectedDeliveryDate) {
      const expectedDate = new Date(record.expectedDeliveryDate)
      const timeDiff = today.getTime() - expectedDate.getTime()
      // 超过7天未交货
      if (timeDiff > 7 * 24 * 60 * 60 * 1000) {
        delayedRecords.push(record)
      }
    }
  })
  
  return delayedRecords
}

// 检查大额采购（超过5万元）
const checkLargeAmountRecords = (records: any[]) => {
  return records.filter(record => record.totalAmount > 50000)
}

// 检查频繁供应商（30天内同一供应商采购超过5次）
const checkFrequentSuppliers = (records: any[]) => {
  const frequentSuppliers: any[] = []
  const supplierPurchaseCount: Record<number, { count: number, records: any[] }> = {}
  const thirtyDaysAgo = new Date()
  thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
  
  // 统计30天内每个供应商的采购次数
  records.forEach(record => {
    // 只统计30天内的采购记录
    const recordDate = new Date(record.inboundDate)
    if (recordDate >= thirtyDaysAgo) {
      if (!supplierPurchaseCount[record.supplierId]) {
        supplierPurchaseCount[record.supplierId] = { count: 0, records: [] }
      }
      supplierPurchaseCount[record.supplierId].count++
      supplierPurchaseCount[record.supplierId].records.push(record)
    }
  })
  
  // 筛选采购次数超过5次的供应商
  Object.keys(supplierPurchaseCount).forEach(supplierId => {
    if (supplierPurchaseCount[parseInt(supplierId)].count > 5) {
      frequentSuppliers.push(...supplierPurchaseCount[parseInt(supplierId)].records)
    }
  })
  
  return frequentSuppliers
}

// 获取提醒图标
const getAlertIcon = (type: string) => {
  const icons: Record<string, any> = {
    delayedDelivery: Warning,
    largeAmount: TrendCharts,
    frequentSupplier: DocumentDelete,
    qualityIssue: InfoFilled
  }
  return icons[type] || Bell
}

// 获取提醒颜色
const getAlertColor = (type: string) => {
  const colors: Record<string, string> = {
    delayedDelivery: '#f5222d',
    largeAmount: '#fa8c16',
    frequentSupplier: '#faad14',
    qualityIssue: '#1890ff'
  }
  return colors[type] || '#1890ff'
}

// 处理提醒点击
const handleAlertClick = (alert: Alert) => {
  ElMessage.info(`查看${alert.title}`)
  emit('alert-click', alert)
}
</script>

<style scoped lang="scss">
.purchase-smart-alerts {
  margin-bottom: 20px;
  
  .alerts-card {
    border: 1px solid #ebeef5;
    border-radius: 8px;
    
    :deep(.el-card__header) {
      padding: 12px 20px;
      border-bottom: 1px solid #ebeef5;
      
      .card-header {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 600;
        color: #1f2d3d;
      }
    }
    
    .alerts-content {
      .alert-item {
        display: flex;
        align-items: flex-start;
        gap: 12px;
        padding: 12px 16px;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s ease;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        &:hover {
          background-color: #f5f7fa;
          transform: translateX(2px);
        }
        
        &.alert-delayedDelivery {
          border-left: 3px solid #f5222d;
        }
        
        &.alert-largeAmount {
          border-left: 3px solid #fa8c16;
        }
        
        &.alert-frequentSupplier {
          border-left: 3px solid #faad14;
        }
        
        &.alert-qualityIssue {
          border-left: 3px solid #1890ff;
        }
        
        .alert-text {
          flex: 1;
          
          .alert-title {
            font-weight: 500;
            color: #1f2d3d;
            margin-bottom: 4px;
            font-size: 14px;
          }
          
          .alert-description {
            font-size: 12px;
            color: #606266;
            line-height: 1.4;
          }
        }
      }
    }
  }
}
</style>